//
//  OutterUploadCVC.swift
//  placepic
//
//  Created by elesahich on 2020/07/08.
//  Copyright © 2020 elesahich. All rights reserved.
//

import UIKit
import YPImagePicker

class OutterUploadPhotoCVC: UICollectionViewCell {
    
    @IBOutlet weak var collectionView: UICollectionView!
    var photoArray: [UIImage]! = []
    var sendphotoClosure: (() -> ()) = {}
    
    override func awakeFromNib() {
        super.awakeFromNib()
        registerCollectionView()
    }
    
    class func topViewController() -> UIViewController? {
        if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
            if var viewController = window.rootViewController {
                while viewController.presentedViewController != nil {
                    viewController = viewController.presentedViewController!
                }
                print("topViewController -> \(String(describing: viewController))")
                return viewController
            }
        }
        return nil
    }
    
    private func registerCollectionView() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        
        let nib = UINib.init(nibName: InnerPhotoUploadCVC.nibName, bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier: InnerPhotoUploadCVC.reuseIdentifier)
    }
    
    private func getImageArray() {
        if UIApplication.shared.windows.first(where: { $0.isKeyWindow }) != nil {
            var config = YPImagePickerConfiguration()
            config.showsPhotoFilters = false
            config.startOnScreen = .library
            config.screens = [.library]
            config.library.defaultMultipleSelection = true
            config.library.maxNumberOfItems = 10
            config.shouldSaveNewPicturesToAlbum = false
            config.targetImageSize = YPImageSize.original
            config.onlySquareImagesFromCamera = false
            config.library.preselectedItems = []
            config.library.preselectedItems = nil


            
            let picker = YPImagePicker(configuration: config)
            
            picker.didFinishPicking { [unowned picker] items, cancelled in
                if cancelled {
                    picker.dismiss(animated: true, completion: nil)
                    return
                }
                for item in items {
                    switch item {
                    case .photo(let p):
                        self.photoArray.append(p.image)
                        guard let pictureArray = self.photoArray else { return }
                        NotificationCenter.default.post(name: .homeSendPhotoNotification, object: nil, userInfo: ["photo": pictureArray])

                    default:
                        print("")
                    }
                }
                picker.dismiss(animated: true)
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            }
            OutterUploadPhotoCVC.topViewController()?.present(picker, animated: true, completion: nil)
        }
    }
}

extension OutterUploadPhotoCVC: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 6
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 6
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == 0 {
            getImageArray()
        }  else {
            collectionView.performBatchUpdates({
                self.collectionView.deleteItems(at: [indexPath])
                self.photoArray.remove(at: indexPath.item - 1)
                guard let pictureArray = photoArray else { return }
                NotificationCenter.default.post(name: .homeSendPhotoNotification, object: nil, userInfo: ["photo": pictureArray])
            }, completion: { _ in
                self.collectionView.reloadData()
            })
        }
    }
}

extension OutterUploadPhotoCVC: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoArray.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let firstCell = collectionView.dequeueReusableCell(withReuseIdentifier: "InnerFirstIndexUploadCVC", for: indexPath)
            as? InnerFirstIndexUploadCVC else { return }
        
        guard let photoCell = collectionView.dequeueReusableCell(withReuseIdentifier: InnerPhotoUploadCVC.reuseIdentifier, for: indexPath)
            as? InnerPhotoUploadCVC else { return }
    
        let returnCell = indexPath.item == 0 ? firstCell : photoCell
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InnerFirstIndexUploadCVC", for: indexPath) as? InnerFirstIndexUploadCVC,
            let photoCell = collectionView.dequeueReusableCell(withReuseIdentifier: InnerPhotoUploadCVC.reuseIdentifier, for: indexPath) as? InnerPhotoUploadCVC
            else { return UICollectionViewCell()
        }
        
        for index in 0..<indexPath.item {
            guard index != photoArray.count else { continue }
            print(index)
            photoCell.bind(photoArray[index])
        }
        
        if indexPath.item == 0 {
            cell.label.text = String(describing: "\(photoArray.count)/10")
            return cell
        }
        else { return photoCell }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 78, height: 78)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14)
    }
}
